﻿using MESMian.Common;
using MESMian.Context;
using MESMian.Forms.ProductionCategory;
using Microsoft.EntityFrameworkCore;
using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.Data;
using System.Drawing;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using System.Windows.Forms;

namespace MESMian.Forms.ProductionSpec
{
    public partial class ProductionSpecList : Form
    {
        public ProductionSpecList()
        {
            InitializeComponent();
            Text = "产品规格";
            Load += ProductionSpecList_Load;
            dtpCreateStart.ValueChanged += DtpCreateStart_ValueChanged;
            dtpCreateEnd.ValueChanged += DtpCreateEnd_ValueChanged;
            btnClearStart.Click += BtnClearStart_Click;
            btnClearEnd.Click += BtnClearEnd_Click;
            ucPager1.PagerEvent += UcPager1_PagerEvent;

            dataGridView1.CellPainting += DataGridView1_CellPainting;
            dataGridView1.CellMouseClick += DataGridView1_CellMouseClick;
        }

        private void DataGridView1_CellMouseClick(object? sender, DataGridViewCellMouseEventArgs e)
        {
            if (e.ColumnIndex >= 0 && e.RowIndex >= 0)
            {
                Point curPosition = e.Location;
                if (dataGridView1.Columns[e.ColumnIndex].Name == "Operate")
                {
                    Graphics g = dataGridView1.CreateGraphics();
                    Font myFont = new Font("宋体", 9F, FontStyle.Regular, GraphicsUnit.Point, 134);
                    SizeF sizeDisable = g.MeasureString("禁用", myFont);
                    SizeF sizeEnable = g.MeasureString("启用", myFont);
                    SizeF sizeModify = g.MeasureString("编辑", myFont);
                    SizeF sizeDetail = g.MeasureString("详情", myFont);
                    float fDisable = sizeDisable.Width / (sizeDisable.Width + sizeEnable.Width + sizeModify.Width + sizeDetail.Width);
                    float fEnable = sizeEnable.Width / (sizeDisable.Width + sizeEnable.Width + sizeModify.Width + sizeDetail.Width);
                    float fModify = sizeModify.Width / (sizeDisable.Width + sizeEnable.Width + sizeModify.Width + sizeDetail.Width);
                    float fDetail = sizeDetail.Width / (sizeDisable.Width + sizeEnable.Width + sizeModify.Width + sizeDetail.Width);

                    Rectangle rectTotal = new Rectangle(0, 0, dataGridView1.Columns[e.ColumnIndex].Width, dataGridView1.Rows[e.RowIndex].Height);
                    RectangleF rectDisable = new RectangleF(rectTotal.Left, rectTotal.Top, rectTotal.Width * fDisable, rectTotal.Height);
                    RectangleF rectEnable = new RectangleF(rectDisable.Right, rectTotal.Top, rectTotal.Width * fEnable, rectTotal.Height);
                    RectangleF rectModify = new RectangleF(rectEnable.Right, rectTotal.Top, rectTotal.Width * fModify, rectTotal.Height);
                    RectangleF rectDetail = new RectangleF(rectModify.Right, rectTotal.Top, rectTotal.Width * fDetail, rectTotal.Height);

                    int primaryKey = Convert.ToInt32(dataGridView1.Rows[e.RowIndex].Cells["ProductCategoryId"].Value);

                    using (var c = new MyContext())
                    {
                        var model = c.ProductSpecs.Find(primaryKey);

                        if (rectDisable.Contains(curPosition))
                        {
                            if (model != null)
                            {
                                if (model.Status == 1)
                                {
                                    MessageBox.Show($"该数据已禁用，不必再次禁用！", "错误", MessageBoxButtons.OK, MessageBoxIcon.Error);
                                    return;
                                }

                                DialogResult dr = MessageBox.Show($"你确定要禁用[编号]={primaryKey}的数据吗？", "确认", MessageBoxButtons.YesNo, MessageBoxIcon.Question);
                                if (dr == DialogResult.Yes)
                                {
                                    model.Status = 1;
                                    model.LastUpdateUserId = LoginInfo.Id;
                                    model.LastUpdateTime = DateTime.Now;
                                    c.Entry(model).State = EntityState.Modified;
                                    c.SaveChanges();
                                    ucPager1.GetPagerData();
                                }
                            }
                        }
                        if (rectEnable.Contains(curPosition))
                        {
                            if (model != null)
                            {
                                if (model.Status == 0)
                                {
                                    MessageBox.Show($"该数据已启用，不必再次启用！", "错误", MessageBoxButtons.OK, MessageBoxIcon.Error);
                                    return;
                                }

                                DialogResult dr = MessageBox.Show($"你确定要启用[编号]={primaryKey}的数据吗？", "确认", MessageBoxButtons.YesNo, MessageBoxIcon.Question);
                                if (dr == DialogResult.Yes)
                                {
                                    model.Status = 0;
                                    model.LastUpdateUserId = LoginInfo.Id;
                                    model.LastUpdateTime = DateTime.Now;
                                    c.Entry(model).State = EntityState.Modified;
                                    c.SaveChanges();
                                    ucPager1.GetPagerData();
                                }
                            }
                        }
                        if (rectModify.Contains(curPosition))
                        {
                            if (model != null)
                            {
                                if (model.Status == 1)
                                {
                                    MessageBox.Show($"该数据已禁用，不能编辑！", "错误", MessageBoxButtons.OK, MessageBoxIcon.Error);
                                    return;
                                }

                                ProductionSpecAddEdit frm = new ProductionSpecAddEdit(primaryKey);
                                if (frm.ShowDialog() == DialogResult.OK) ucPager1.GetPagerData();
                            }
                        }
                        if (rectDetail.Contains(curPosition))
                        {
                            if (model != null)
                            {
                                ProductionSpecDetail frm = new ProductionSpecDetail(primaryKey);
                                frm.ShowDialog();
                            }
                        }
                    }
                }
            }
        }

        private void UcPager1_PagerEvent(int currentPage, int pageSize, out int totalCount)
        {
            using(var mtx =new MyContext())
            {
                var query = from item in mtx.ProductSpecs
                            orderby item.ProductSpecId ascending
                            join u1 in mtx.Users on item.CreateUserId equals u1.CreateUserId
                            into result1
                            from item1 in result1.DefaultIfEmpty()
                            join u2 in mtx.Users on item.LastUpdateUserId equals u2.UserId
                            into result2
                            from item2 in result2.DefaultIfEmpty()
                            select new
                            {
                                item.ProductSpecId,
                                item.ProductSpecName,
                                item.Status,
                                StatusText = item.Status == 0 ? "正常" : "禁用",
                                item.CreateUserId,
                                CreateUserName = item1 != null ? item1.UserName : null,
                                item.CreateTime,
                                item.LastUpdateUserId,
                                LastUpdateUserName = item2 != null ? item2.UserName : null,
                                item.LastUpdateTime,
                            };

                totalCount = query.Count();
                query = query.Skip((ucPager1.CurrentPage - 1) * ucPager1.PageSize).Take(ucPager1.PageSize);
                dataGridView1.DataSource = query.ToList();

                dataGridView1.Columns["Status"].Visible = false;
                dataGridView1.Columns["CreateUserId"].Visible = false;
                dataGridView1.Columns["LastUpdateUserId"].Visible = false;

                dataGridView1.Columns["ProductSpecId"].HeaderText = "编号";
                dataGridView1.Columns["ProductSpecName"].HeaderText = "产品类型名称";
                dataGridView1.Columns["Status"].HeaderText = "状态值";
                dataGridView1.Columns["StatusText"].HeaderText = "状态";
                dataGridView1.Columns["CreateUserId"].HeaderText = "创建人Id";
                dataGridView1.Columns["CreateUserName"].HeaderText = "创建人";
                dataGridView1.Columns["CreateTime"].HeaderText = "创建日期";
                dataGridView1.Columns["LastUpdateUserId"].HeaderText = "修改人Id";
                dataGridView1.Columns["LastUpdateUserName"].HeaderText = "修改人";
                dataGridView1.Columns["LastUpdateTime"].HeaderText = "修改日期";


                dataGridView1.Columns["ProductSpecId"].Width = 100;
                dataGridView1.Columns["CreateTime"].Width = 200;
                dataGridView1.Columns["LastUpdateTime"].Width = 200;

                if (!dataGridView1.Columns.Contains("Operate"))
                {
                    dataGridView1.Columns.Add("Operate", "操作");
                    dataGridView1.Columns["Operate"].Width = 200;
                }
            }
        }

        private void DataGridView1_CellPainting(object? sender, DataGridViewCellPaintingEventArgs e)
        {
            if (e.ColumnIndex >= 0 && e.RowIndex >= 0)
            {
                if (dataGridView1.Columns[e.ColumnIndex].Name == "Operate")
                {
                    StringFormat sf = (StringFormat)StringFormat.GenericDefault.Clone();
                    sf.Alignment = StringAlignment.Center;
                    sf.LineAlignment = StringAlignment.Center;
                    sf.Trimming = StringTrimming.EllipsisCharacter;

                    e.PaintBackground(e.CellBounds, false);

                    Font myFont = new Font("微软雅黑", 9F, FontStyle.Regular, GraphicsUnit.Pixel);
                    if (e.Graphics != null)
                    {
                        SizeF sizeDisable = e.Graphics.MeasureString("禁用", myFont);
                        SizeF sizeEnable = e.Graphics.MeasureString("启用", myFont);
                        SizeF sizeModify = e.Graphics.MeasureString("编辑", myFont);
                        SizeF sizeDetail = e.Graphics.MeasureString("详情", myFont);

                        float fDisable = sizeDisable.Width / e.CellBounds.Width;
                        float fEnable = sizeEnable.Width / e.CellBounds.Width;
                        float fModify = sizeModify.Width / e.CellBounds.Width;
                        float fDetail = sizeDetail.Width / e.CellBounds.Width;

                        RectangleF rectDisable = new RectangleF(e.CellBounds.Left, e.CellBounds.Top, e.CellBounds.Width * fDisable, e.CellBounds.Height);
                        RectangleF rectEnable = new RectangleF(rectDisable.Right, e.CellBounds.Top, e.CellBounds.Width * fEnable, e.CellBounds.Height);
                        RectangleF rectModify = new RectangleF(rectEnable.Right, e.CellBounds.Top, e.CellBounds.Width * fModify, e.CellBounds.Height);
                        RectangleF rectDetail = new RectangleF(rectModify.Right, e.CellBounds.Top, e.CellBounds.Width * fDetail, e.CellBounds.Height);

                        e.Graphics.DrawString("禁用", myFont, Brushes.Red, rectDisable, sf);
                        e.Graphics.DrawString("启用", myFont, new SolidBrush(Color.FromArgb(255, 207, 73)), rectDisable, sf);
                        e.Graphics.DrawString("编辑", myFont, new SolidBrush(Color.FromArgb(201, 148, 246)), rectDisable, sf);
                        e.Graphics.DrawString("详情", myFont, new SolidBrush(Color.FromArgb(24, 52, 93)), rectDisable, sf);

                    }

                }
            }
        }

        private void BtnClearEnd_Click(object? sender, EventArgs e)
        {
            dtpCreateEnd.CustomFormat = " ";
        }

        private void BtnClearStart_Click(object? sender, EventArgs e)
        {
            dtpCreateEnd.CustomFormat = " ";
        }

        private void DtpCreateEnd_ValueChanged(object? sender, EventArgs e)
        {
            dtpCreateEnd.CustomFormat = "yyyy-MM-dd";
        }

        private void DtpCreateStart_ValueChanged(object? sender, EventArgs e)
        {
            dtpCreateStart.CustomFormat = "yyyy-MM-dd";
        }

        private void ProductionSpecList_Load(object? sender, EventArgs e)
        {
            BindStatus();
            SettingDateFormat();
            ucPager1.GetPagerData();
        }

        private void SettingDateFormat()
        {
            dtpCreateStart.Format = DateTimePickerFormat.Custom;
            dtpCreateStart.CustomFormat = " ";
            dtpCreateEnd.Format = DateTimePickerFormat.Custom;
            dtpCreateEnd.CustomFormat = " ";
        }

        private void BindStatus()
        {
            cbbStatus.Items.Clear();
            List<Status> item = new List<Status>
            {
                new Status(){Text = "正常",Code=0},
                new Status{Text ="禁用",Code=1},
                new Status{Text = "全部",Code =-1}
            };
            cbbStatus.DataSource = item;
            cbbStatus.DisplayMember = "Text";
            cbbStatus.ValueMember = "Code";
        }

    }
}
